package vn.buffalocoders.rikos.ui.category;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Map;


import vn.buffalocoders.rikos.R;
import vn.buffalocoders.rikos.ui.category.slidemenu.SlideMenu;
import vn.buffalocoders.rikos.ui.common.*;
import vn.buffalocoders.rikos.ui.common.CustomOptionMenu.OnMenuItemSelectedListener;
import vn.buffalocoders.rikos.ui.home.HomeActivity;
import vn.buffalocoders.rikos.ui.mylibrary.MyLibraryActivity;
import vn.buffalocoders.rikos.ui.network.ConnectRikoServer;
import vn.buffalocoders.rikos.ui.network.HttpMultipartPost;
import android.app.Activity;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import vn.buffalocoders.rikos.ui.category.slidemenu.SlideMenuInterface.OnSlideMenuItemClickListener;
import vn.buffalocoders.rikos.ui.common.fileexplorer.*;
import vn.buffalocoders.rikos.ui.common.sessions.SessionManager;


public class CategoryActivity extends Activity  implements OnClickListener, OnMenuItemSelectedListener, OnSlideMenuItemClickListener {
	private static final int REQUEST_PATH = 1;
	private static final int SLIDE_MENU_DURATION = 250;

	private RelativeLayout mRelativeLayoutMenu = null;
	private HorizontalScrollView mScrollViewMenu = null;
	private LinearLayout mLinearLayoutBtns = null;
	private CustomOptionMenu mOptionMenu = null;
	private SlideMenu mSlideMenu;

	GridView gridView;
	public static final int CATE_LASTED = 0;
	public static final int CATE_MOST_VIEW = 1;
	public static final int CATE_CATE_ID = 2;

	public static final int MENU_ITEM_1 = 1;
	public static final int MENU_ITEM_2 = 2;
	public static final int MENU_ITEM_3 = 3;
	public static final int MENU_ITEM_4 = 4;
	public static final int MENU_ITEM_5 = 5;
	public static final int MENU_ITEM_6 = 6;
	public static final int MENU_ITEM_7 = 7;
	public static final int MENU_ITEM_8 = 8;

	private GetCategoryTask mCategoryTask = null;
	private GetCategoryListTask mCategoryListTask = null;
	private UploadAvatarTask mUploadAvatarTask = null;

	private int catetask;
	private String view;;
	private String like;
	private String page;
	private String id;
	private HttpMultipartPost post;
	private Activity thisactivity = null;

	private SessionManager session;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_category);		
		thisactivity = this;			 
		this.catetask = CATE_LASTED;

		session = new SessionManager(CategoryActivity.this);
		/**
		 * Call this function whenever you want to check user login
		 * This will redirect user to LoginActivity is he is not
		 * logged in
		 * */
		if (!session.isLoggedIn()) {
			Intent intent = new Intent(CategoryActivity.this, HomeActivity.class);
			startActivity(intent);
			finish();
		}

		if (((FacebookApplication) getApplication()).getListBook() == null)
		{
			mCategoryTask = new GetCategoryTask();
			mCategoryTask.execute((Void) null);
		}
		else
		{
			gridView = (GridView) findViewById(R.id.gridView);		 
			gridView.setAdapter(new BookAdapter(thisactivity, ((FacebookApplication) getApplication()).getListBook()));
		}

		mSlideMenu = (SlideMenu) findViewById(R.id.slideMenu);
		mSlideMenu.init(this, R.menu.slide, this, SLIDE_MENU_DURATION);

		Button btnmostviews = (Button)findViewById(R.id.btnmostviews);
		btnmostviews.setOnClickListener(this);

		Button btnlastest = (Button) findViewById(R.id.btnlastest);
		btnlastest.setOnClickListener(this);

		Button btncategory = (Button) findViewById(R.id.btncategory);
		btncategory.setOnClickListener(this);

		ImageView slidemenu = (ImageView) findViewById(R.id.img_slidemenu);
		slidemenu.setOnClickListener(this);

		TextView txtsearch = (TextView) findViewById(R.id.txt_search);
		txtsearch.setOnClickListener(this);

		ImageView img_search = (ImageView) findViewById(R.id.img_search);
		img_search.setOnClickListener(this);

		/*
		 * Initialize Custom Option Menu
		 */
		mRelativeLayoutMenu = (RelativeLayout) findViewById(R.id.top_layout);
		mScrollViewMenu = (HorizontalScrollView) findViewById(R.id.scrollViewMenu);
		mLinearLayoutBtns = (LinearLayout) findViewById(R.id.linearLayoutBtns);
		mRelativeLayoutMenu.setVisibility(View.INVISIBLE);
		mOptionMenu = new CustomOptionMenu(this, mLinearLayoutBtns, this, getLayoutInflater(), findViewById(R.id.scrollViewMenu).getLayoutParams().height);

		mScrollViewMenu.setHorizontalScrollBarEnabled(false);

		findViewById(R.id.top_layout).setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// Close the menu when touch out side
				// mRelativeLayoutMenu.setVisibility(View.INVISIBLE);
				return false;
			}
		});

		findViewById(R.id.img_close_menu).setOnClickListener(this);
		findViewById(R.id.linearLayoutCloseMenu).setOnClickListener(this);
	}

	public class GetCategoryTask extends AsyncTask<Void /* param */, Void /* Progress */,ArrayList<RikoBook>  /* Result */> {


		@Override
		protected ArrayList<RikoBook>  doInBackground(Void... param) {
			// TODO Auto-generated method stub
			Log.i("DBT_TEST", String.format("GetCategoryTask authToken=%s,userID=%s ", session.getAuthToken(), session.getUserId()));		
			if(catetask == CATE_LASTED){
				return ConnectRikoServer.getBookWithCategory(session.getAuthToken(), session.getUserId());
			}

			if(catetask == CATE_MOST_VIEW){
				view = "true";
				return ConnectRikoServer.getBookWithCategory(session.getAuthToken(), session.getUserId(), catetask, id, view, like, page);
			}

			if(catetask == CATE_CATE_ID){
				return ConnectRikoServer.getBookWithCategory(session.getAuthToken(), session.getUserId(), catetask, id, view, like, page);
			}


			return null;

		}

		@Override
		protected void onPostExecute(ArrayList<RikoBook> listbooks) {
			mCategoryTask = null;
			if (listbooks == null) {
				Log.i("DBT_TEST", String.format("listbook NULL "));			
			}
			else {
				Log.i("DBT_TEST", String.format("listbook NOT NULL "));			
				((FacebookApplication) getApplication()).setListBook(listbooks);
				setUI();
			}
		}

		@Override
		protected void onCancelled() {
			mCategoryTask = null;
		}

		protected void setUI(){
			Log.i("DBT_TEST", String.format("Set UI"));			
			gridView = (GridView) findViewById(R.id.gridView);		 
			gridView.setAdapter(new BookAdapter(thisactivity, ((FacebookApplication) getApplication()).getListBook()));			
		}
	}

	public class GetCategoryListTask extends AsyncTask<Void /* param */, Void /* Progress */,ArrayList<RikoCategory>  /* Result */> {


		@Override
		protected ArrayList<RikoCategory>  doInBackground(Void... param) {
			// TODO Auto-generated method stub
			Log.i("LETRUONG", String.format("GetCategoryListTask authToken=%s,userID=%s ", session.getAuthToken(), session.getUserId()));			
			return ConnectRikoServer.getCategoryList(session.getAuthToken(), session.getUserId());
		}

		@Override
		protected void onPostExecute(ArrayList<RikoCategory> listCategories) {
			mCategoryListTask = null;
			if (listCategories == null) {
				Log.i("LETRUONG", String.format("listcategory NULL "));			
			}
			else {
				loadMenuItems(listCategories);
				mRelativeLayoutMenu.setVisibility(View.VISIBLE);
			}
		}

		@Override
		protected void onCancelled() {
			mCategoryListTask = null;
		}

	}

	/**
	 * 
	 * @author HoangTuanSu
	 * 
	 */
	public class UploadAvatarTask extends AsyncTask<Void /* param */, Void /* Progress */,Map<String, String>  /* Result */> {


		@Override
		protected Map<String, String>  doInBackground(Void... param) {
			// TODO Auto-generated method stub
			String path = getRealPathFromURI(mSlideMenu.mImageCaptureUri); //from Gallery

			if (path == null)
				path = mSlideMenu.mImageCaptureUri.getPath(); //from File Manager

			return ConnectRikoServer.uploadAvatar(session.getAuthToken(), session.getUserId(), path);
		}

		@Override
		protected void onPostExecute(final Map<String, String> result) {
			mUploadAvatarTask = null;

		}

		@Override
		protected void onCancelled() {
			mUploadAvatarTask = null;
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) { 
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			if ( mRelativeLayoutMenu.getVisibility() == View.INVISIBLE ) {
				//mCategoryListTask = new GetCategoryListTask();
				//mCategoryListTask.execute((Void) null);
			}
			else {
				// mRelativeLayoutMenu.setVisibility(View.INVISIBLE);
			}
			return true; // disable Menu default
		}
		return super.onKeyDown(keyCode, event); 
	} 

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		// getMenuInflater().inflate(R.menu.category, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId() == R.id.btnmostviews) {
			catetask = CATE_MOST_VIEW;			
			mCategoryTask = new GetCategoryTask();
			mCategoryTask.execute((Void) null);
		}
		else if (v.getId() == R.id.btnlastest) {
			catetask = CATE_LASTED;			
			mCategoryTask = new GetCategoryTask();
			mCategoryTask.execute((Void) null);
		}else if (v.getId() == R.id.btncategory) {
			mCategoryListTask = new GetCategoryListTask();
			mCategoryListTask.execute((Void) null);
		}else if (v.getId() == R.id.txt_search) {
			Toast.makeText(this, "Searching", Toast.LENGTH_LONG).show();
		}else if (v.getId() == R.id.img_search) {
			Toast.makeText(this, "Search", Toast.LENGTH_LONG).show();
		}else if (v.getId() == R.id.img_slidemenu) {
			if(!mSlideMenu.menuIsShown)
				mSlideMenu.show();
		}else if (v.getId() == R.id.img_close_menu || v.getId() == R.id.linearLayoutCloseMenu) {
			mRelativeLayoutMenu.setVisibility(View.INVISIBLE);
		}
	}

	private void loadMenuItems(ArrayList<RikoCategory> listCategories) {
		ArrayList<CustomOptionMenuItem> menuItems = new ArrayList<CustomOptionMenuItem>();
		for (int i = 0; i < listCategories.size(); i++) {
			CustomOptionMenuItem cmi = new CustomOptionMenuItem();
			cmi.setCaption(listCategories.get(i).getName());
			cmi.setImageURL(listCategories.get(i).getImageName());
			cmi.setId(listCategories.get(i).getID());
			menuItems.add(cmi);
		}

		try {
			mOptionMenu.setMenuItems(menuItems);
			mOptionMenu.initOptionMenu();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public void MenuItemSelectedEvent(CustomOptionMenuItem selection) {
		// TODO Auto-generated method stub
		id = String.format("%d", selection.getId());
		catetask = CATE_CATE_ID;			
		mCategoryTask = new GetCategoryTask();
		mCategoryTask.execute((Void) null);
		mRelativeLayoutMenu.setVisibility(View.INVISIBLE);
	}

	@Override
	public void onSlideMenuItemClick(int itemId) {
		Intent intent = null;
		switch(itemId) {
		case R.id.item_vietsach:
			Toast.makeText(this, "Item one selected", Toast.LENGTH_SHORT).show();
			break;
		case R.id.item_tusachcongdong:
			Toast.makeText(this, "Item two selected", Toast.LENGTH_SHORT).show();
			break;
		case R.id.item_sachcuatoi:
			intent = new Intent(CategoryActivity.this, MyLibraryActivity.class);
			startActivity(intent);
			break;
		case R.id.item_yeuthich:
			Toast.makeText(this, "Item four selected", Toast.LENGTH_SHORT).show();
			break;
		case R.id.item_cauhinh:
			Intent intent1 = new Intent(this, FileChooser.class);

			startActivityForResult(intent1, REQUEST_PATH);
			break;
		case R.id.item_logout:
			session.logoutUser();
			intent = new Intent(CategoryActivity.this, HomeActivity.class);
			startActivity(intent);
			finish();
			break;
		}

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data){
		if (resultCode != RESULT_OK) {
			return;
		}
		// See which child activity is calling us back.
		if (requestCode == REQUEST_PATH){
			String curFileName = data.getStringExtra(ConstantsHelper.FILE_NAME_FROM_SLIDER); 
			String curPathName = data.getStringExtra(ConstantsHelper.PATH_NAME_FROM_SLIDER);
			String filePath = String.format("%s/%s", curPathName, curFileName);//"/storage/sdcard0/updateAdtech/orgpic/1.png";
			//String url = "http://service.ireadhome.com/api/Upload/Image";
			File file = new File(filePath);
			if (file.exists()) {
				post = new HttpMultipartPost(CategoryActivity.this, 
						filePath, ConnectRikoServer.URL_ADD_LIBARY, 
						session.getAuthToken(), session.getUserId(), ConnectRikoServer.PARAM_BOOK_FILE, 
						"Uploading book");
				post.execute();
			} else {
				Toast.makeText(CategoryActivity.this, "Uploadfile", Toast.LENGTH_LONG)
				.show();
			}
			Log.i("LETRUONG", String.format("curFileName=%s, pathName=%s", curFileName, curPathName));
		} else {
			Bitmap bitmap   = null;
			String path     = "";
			if (requestCode == SlideMenu.PICK_FROM_FILE) {
				mSlideMenu.mImageCaptureUri = data.getData();
				path = getRealPathFromURI(mSlideMenu.mImageCaptureUri); //from Gallery

				if (path == null)
					path = mSlideMenu.mImageCaptureUri.getPath(); //from File Manager

				if (path != null)
					bitmap  = BitmapFactory.decodeFile(path);
				try {
					copyFile(path, Environment.getExternalStorageDirectory() + "/tmp_avatar_riko.jpg");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					Log.d("[CategoryActivity] - onActivityResult:", e.getMessage());
				}
			} else {
				path    = mSlideMenu.mImageCaptureUri.getPath();
				bitmap  = BitmapFactory.decodeFile(path);
			}

			if(bitmap != null) {
				int nh = (int) ( bitmap.getHeight() * (512.0 / bitmap.getWidth()) );
				Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
				mSlideMenu.mAvatarImage.setImageBitmap(scaled);
			}
		}
	}

	
	public void copyFile(String selectedImagePath, String string) throws IOException {
        InputStream in = new FileInputStream(selectedImagePath);
        OutputStream out = new FileOutputStream(string);

        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
      }
	
	public String getRealPathFromURI(Uri contentUri) {
		String [] proj      = {MediaStore.Images.Media.DATA};
		Cursor cursor       = managedQuery( contentUri, proj, null, null,null);

		if (cursor == null) return null;

		int column_index    = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

		cursor.moveToFirst();

		return cursor.getString(column_index);
	}

}


